<template>
  <div>
    <a-modal title-align="start" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="1140">
      <template #title>
        <a-space>
          <span>{{ title }}</span>
          <CopyText :val="props.info.code" v-if="props.type == 'edit'">
            <template #defaultVal>{{ props.info.code }}</template>
          </CopyText>
        </a-space>
      </template>
      <div class="hd">
        <div class="text-desc">
          <span class="required">选择任务产品：</span>
          <span class="common-text">围绕该产品发布任务，所以任务产品是必填项</span>
        </div>
        <div class="sku-info-con">
          <div class="left">
            <div class="input-serch" v-if="props.type != 'edit'">
              <a-input-search placeholder="请输入SKU" v-model="sku" @press-enter="searchSku" @search="searchSku" />
            </div>
            <div class="show-sku-info">
              <div v-if="skuInfo.id">
                <div class="top">
                  <div class="img">
                    <ImgPopover :src="imgUrl">
                      <template #con>
                        <a-image :preview="false" width="60" height="60" fit="contain" :src="imgUrl" />
                      </template>
                    </ImgPopover>
                  </div>
                  <div class="descriptions">
                    <a-descriptions size="mini" :data="descriptionsData" :column="2" :label-style="{ textAlign: 'right' }">
                      <template #label="{ label, data }">
                        <div>{{ label }}：</div>
                      </template>
                      <template #value="{ value, data }">
                        <div v-if="data.label == '名称'" style="width: 300px">
                          <TextLimit position="top" :rows="1">{{ skuInfo.skuName }}</TextLimit>
                        </div>
                        <div v-if="data.label == 'SPU'">
                          {{ skuInfo.spu }}
                        </div>
                        <div v-if="data.label == 'SKU'">
                          {{ skuInfo.sku }}
                        </div>
                        <div v-if="data.label == '类目'">
                          {{ $extract(skuInfo, 'category.name') }}
                        </div>
                        <div v-if="data.label == '主开发'">
                          {{ $extract(skuInfo, 'developer.name') }}
                        </div>
                        <div v-if="data.label == '首次入FBA仓日期'">
                          {{ $setTime(skuInfo.gmtWarehousing) }}
                        </div>
                      </template>
                    </a-descriptions>
                  </div>
                </div>
                <div class="bottom mt10" v-if="props.type == 'edit'">
                  <!-- <span>橱窗图:{{ skuInfo.productPicList ? skuInfo.productPicList.length : '0' }}</span>
                  <span>原图:{{ artworkMasterNum }}</span>
                  <span>手绘稿:{{ sketchNum }}</span>
                  <span>CAD文件:{{ cadNum }}</span> -->
                  <span style="margin-right: 40px">采购下单时间：{{ $setTime($extract(skuInfo, 'gmtPurchase')) }}</span>
                  <span style="margin-right: 40px">采购入库时间：{{ $setTime($extract(skuInfo, 'gmtPurchaseWarehouse')) }}</span>
                  <span style="margin-right: 40px">货件发货时间：{{ $setTime($extract(skuInfo, 'gmtShipmentShipped')) }}</span>
                  <span>货件入库时间：{{ $setTime($extract(skuInfo, 'gmtShippmentWarehouse')) }}</span>
                </div>
              </div>
              <div v-else>
                <a-empty description="请输入sku查询产品信息" />
              </div>
            </div>
          </div>
          <div class="right">
            <div>{{ $extract(walletInfo, 'consumeWalletAccount.userName') }}账户可用余额</div>
            <div class="price">￥{{ price }}</div>
          </div>
        </div>
      </div>
      <div class="bd">
        <a-tabs v-model:active-key="curtab" @tab-click="tabClick" v-if="props.type == 'add'">
          <a-tab-pane v-for="item of tabList" :key="item.value" :title="item.label"> </a-tab-pane>
        </a-tabs>
        <component :is="tabList.find((e:any) => e.value == curtab).com" ref="tabCom" :type="props.type" :configInfo="configInfo" :searchSku="searchSku" />
      </div>
      <template #footer>
        <a-button @click="showvisible = false">返回</a-button>
        <a-button type="primary" :loading="saveOrUpdateSubmitTaskLoading" @click="saveOrUpdateSubmitTask">保存任务暂不发布</a-button>
        <a-button type="primary" :loading="publishSubmitTaskLoading" @click="showPublishModal">立即发布任务</a-button>
      </template>

      <a-modal title="提示" title-align="start" v-model:visible="showPublishTaskVisiable" @ok="publishSubmitTask" @cancel="showPublishTaskVisiable = false">
        <div>发布任务需要从{{ $extract(walletInfo, 'consumeWalletAccount.userName') }}账户冻结服务费用￥{{ amtCost }}</div>
      </a-modal>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted, provide, nextTick } from 'vue'
  import { getSkuDetailBySku } from '@/api/product'
  import { findCompanyGroupWalletByUserId } from '@/api/finance/wallet'
  import { saveOrUpdateTask, publishTask, getTaskById, getPlatTaskConfigByTaskType } from '@/api/task'
  import { Message } from '@arco-design/web-vue'
  import useUserStore from '@/store/modules/user'
  import NewCollection from './newCollection.vue'
  import Artwork from './artwork.vue'
  import QuickRetouching from './quickRetouching.vue'
  import ShootVideo from './shootVideo.vue'
  import _ from 'lodash-es'
  let props = defineProps(['modelValue', 'type', 'info'])
  let emits = defineEmits(['save', 'update:modelValue'])
  const tabCom = ref()

  let sku = ref('')
  const userInfo = useUserStore()
  let price: any = ref('')
  let amtCost: any = ref()
  let saveOrUpdateSubmitTaskLoading: any = ref(false)
  let publishSubmitTaskLoading: any = ref(false)
  let showPublishTaskVisiable: any = ref(false)
  let curtab: any = ref('NEW_PRODUCT_PICTURE')
  let tabList: any = ref([
    { label: '新品套图任务', value: 'NEW_PRODUCT_PICTURE', com: NewCollection },
    { label: '快速修图任务', value: 'QUICK_FIX_PICTURE', com: QuickRetouching },
    { label: '原图任务', value: 'ORIGINAL_PICTURE', com: Artwork },
    { label: '拍摄视频任务', value: 'SHOOT_VIDEO', com: ShootVideo },
  ])
  let skuInfo: any = ref({})
  let itemInfo: any = ref({})
  let configInfo: any = ref({})
  let walletInfo: any = ref({})
  let title = ref('')
  let imgUrl = ref()
  let descriptionsData = ref([
    { label: '名称', value: '' },
    { label: 'SPU', value: '' },
    { label: 'SKU', value: '' },
    { label: '类目', value: '' },
    { label: '主开发', value: '' },
    // { label: '首次入FBA仓日期', value: '' },
  ])
  provide('skuInfo', skuInfo)
  provide('type', props.type)
  provide('taskDetailInfo', itemInfo)
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  let artworkMasterNum = computed(() => {
    let arr = skuInfo.value.productSpu?.productInfoList || []
    return arr.filter((e: any) => e.type == '原图').length
  })
  let sketchNum = computed(() => {
    let arr = skuInfo.value.productSpu?.productInfoList || []
    return arr.filter((e: any) => e.type == '手绘稿').length
  })
  let cadNum = computed(() => {
    let arr = skuInfo.value.productSpu?.productInfoList || []
    return arr.filter((e: any) => e.type == 'CAD').length
  })

  const searchSku = async () => {
    if (!sku.value) {
      return Message.error('请输入sku')
    }
    const res: any = await getSkuDetailBySku(sku.value || skuInfo?.sku)
    skuInfo.value = {}
    skuInfo.value = res?.data || {}
    imgUrl.value = skuInfo.value.productPicList instanceof Array ? skuInfo.value.productPicList[0].url : ''
  }

  const initWallet = async () => {
    const res: any = await findCompanyGroupWalletByUserId({ companyId: userInfo.companyId })
    walletInfo.value = res.data || {}
    let consumeWalletAccountBalance = res.data?.consumeWalletAccount?.availabeBalance || 0
    let giftWalletAccountBalance = res.data?.giftWalletAccount?.availabeBalance || 0
    price.value = consumeWalletAccountBalance + giftWalletAccountBalance
  }

  const saveOrUpdateSubmitTask = async () => {
    let info: any = tabCom.value.getOrSetInfo()
    // 必填校验没通过
    if (!info) return
    const arr = skuInfo?.value.productSpu?.productInfoList || []
    let productPicList = skuInfo?.value?.productPicList || []
    let originPicList = arr.filter((e: any) => e.type == '原图')
    let handDrawList = arr.filter((e: any) => e.type == '手绘稿')
    let cadList = arr.filter((e: any) => e.type == 'CAD')
    let params = {
      type: curtab.value,
      product: {
        productPicList: productPicList,
        originPicList: originPicList,
        handDrawList: handDrawList,
        cadList: cadList,
        category: skuInfo?.value.category,
        gmtWarehousing: skuInfo?.value.gmtWarehousing,
        id: skuInfo.value.id,
        sku: skuInfo.value.sku,
        spu: skuInfo.value.spu,
        skuName: skuInfo.value.skuName,
        spuName: skuInfo.value?.productSpu?.spuName,
        developer: skuInfo.value?.developer || {},
      },
      ...itemInfo.value,
      ...info,
    }
    // let isSampleType = params.newProductPicTask?.outOriginalType || params.originalPicTask?.outOriginalType || params.quickFixPicTask?.outOriginalType || params.shootViedoTask?.outOriginalType
    // params.type != 'QUICK_FIX_PICTURE' && isSampleType == 'REAL_SHOOT' ? (params.isSample = true) : (params.isSample = false)

    try {
      saveOrUpdateSubmitTaskLoading.value = true
      await saveOrUpdateTask(params)
      props.type == 'add' ? Message.success('保存成功') : Message.success('编辑成功')
      emits('save')
      showvisible.value = false
    } catch (error) {}
    saveOrUpdateSubmitTaskLoading.value = false
  }

  const publishSubmitTask = async () => {
    let info: any = tabCom.value.getOrSetInfo()
    // 必填校验没通过
    if (!info) return

    const arr = skuInfo?.value.productSpu?.productInfoList || []
    let productPicList = skuInfo?.value?.productPicList || []
    let originPicList = arr.filter((e: any) => e.type == '原图')
    let handDrawList = arr.filter((e: any) => e.type == '手绘稿')
    let cadList = arr.filter((e: any) => e.type == 'CAD')
    let params = {
      type: curtab.value,
      product: {
        productPicList: productPicList,
        originPicList: originPicList,
        handDrawList: handDrawList,
        cadList: cadList,
        category: skuInfo?.value.category,
        gmtWarehousing: skuInfo?.value.gmtWarehousing,
        id: skuInfo.value.id,
        sku: skuInfo.value.sku,
        spu: skuInfo.value.spu,
        skuName: skuInfo.value.skuName,
        spuName: skuInfo.value?.productSpu?.spuName,
        developer: skuInfo.value?.developer || {},
      },
      ...itemInfo.value,
      ...info,
    }
    try {
      publishSubmitTaskLoading.value = true
      await publishTask(params)
      Message.success('发布成功')
      emits('save')
      showvisible.value = false
    } catch (error) {}
    publishSubmitTaskLoading.value = false
  }

  const getDetail = async () => {
    const res: any = await getTaskById({ id: props.info.id })
    itemInfo.value = res?.data || {}
    skuInfo.value = itemInfo.value?.product || {}
    imgUrl.value = skuInfo.value.productPicList instanceof Array ? skuInfo.value.productPicList[0]?.url : ''
    tabCom.value.getOrSetInfo(itemInfo.value)
  }

  const init = () => {
    if (props.type == 'add') {
      title.value = '新建任务'
    } else {
      let titleName = tabList.value.find((e: any) => props.info.type == e.value).label
      title.value = `编辑${titleName}`
      curtab.value = props.info.type
      getDetail()
      sku.value = props.info.product.sku
      // searchSku()
    }
  }

  const showPublishModal = () => {
    // let info: any = tabCom.value.getOrSetInfo()
    // // 必填校验没通过
    // if (!info) return
    amtCost = tabCom.value.getPrice()
    showPublishTaskVisiable.value = true
  }

  const tabClick = () => {
    let obj = _.cloneDeep(skuInfo.value)
    skuInfo.value = {}
    nextTick(() => {
      skuInfo.value = obj
    })
  }

  onMounted(() => {
    // 初始化剩余钱包金额
    initWallet()
    init()
  })
</script>

<style lang="less" scoped>
  .common-text {
    font-size: 12px;
    color: #a39999;
  }
  .sku-info-con {
    min-height: 100px;
    display: flex;
    justify-content: space-between;
    .left {
      // height: 100%;
      width: 900px;
      display: flex;
      border: 1px solid #d7d7d7;
      padding: 5px;
      .input-serch {
        width: 180px;
      }
      .show-sku-info {
        flex: 1;
        margin-left: 10px;
        .top {
          height: 55px;
          width: 100%;
          display: flex;
          .img {
            width: 60px;
            height: 60px;
          }
          .descriptions {
            flex: 1;
            margin-left: 10px;
          }
        }
        .bottom {
          height: 40px;
          font-size: 12px;
          line-height: 20px;
          // margin-left: 70px;
          color: var(--color-text-3);
          span {
            display: inline-block;
            margin-right: 10px;
          }
        }
      }
    }
    .right {
      flex: 1;
      border: 1px solid #d7d7d7;
      padding: 5px;
      .price {
        font-size: 25px;
        color: red;
      }
    }
  }
</style>
